package com.jinxin.platform.cdacsrecord.core.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.CommonCodeEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.Constant;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.ResultEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.*;
import com.jinxin.platform.cdacsrecord.core.service.AcsControlModuleInvokeService;
import com.jinxin.platform.cdacsrecord.core.service.RestTemplateService;
import com.jinxin.platform.cdacsrecord.core.utils.RestTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Description: apcos-cdjurenacs
 * Created by 34759 on 2020/8/7 10:59
 */
@Slf4j
@CrossOrigin
@RequestMapping("/unAuth/jrApp")
@RestController
public class UnauthAppInterface {
    @Value("${cdacsrecord.url-info.listByToken}")
    private String listByToken;
    //common-host
    @Value("${cdacsrecord.url-info.appHost}")
    private String commonHost;
    @Value("${cdacsrecord.url-info.imgHost}")
    private String imgHost;


    @Autowired
    private RestTemplateService templateService;
    @Autowired
    private AcsControlModuleInvokeService acsControlModuleInvokeService;

    @GetMapping("/getImgCode")
    public void getImgCode(HttpServletRequest request, HttpServletResponse response ){
        RestTemplate client = new RestTemplate();
        ResponseEntity<Resource> entity = client.getForEntity(commonHost+"/base/baseImgVcode.do", Resource.class);
        try {
            InputStream in = entity.getBody().getInputStream();
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[in.available()];
            out.write(b);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取小区列表
    @PostMapping("/getCommuList")
    public ResultEntity getCommuList( ){
       String etoToken =  templateService.getEtoToken(true);
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("bopType", 1);
        params.add("etoToken", etoToken);
        AppResultVO resultVO = RestTemplateUtils.sendRequest(listByToken, params,AppResultVO.class,"post");
        log.info(resultVO.toString() );
        if(resultVO != null){
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                List<JRCommunity> comList = JSON.parseArray( JSONArray.toJSONString(resultVO.getObject()) , JRCommunity.class);
                log.info(comList.toString());
                List<JRCommunity> resComList = new ArrayList<>();
                for(JRCommunity community: comList ){
                    if(null != community && null != community.getCpId() ){
                        resComList.add(community);
                    }
                }
                return new ResultEntity(CommonCodeEntity.SUC_CODE, "suc",resComList);
            }else {
                log.error("getEtoToken fail: " + resultVO.toString());
            }
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"fail","" );
    }

    // 用户登录
    @PostMapping("/appDoLogin")
    public ResultEntity appDoLogin(AppPhoneLoginVO loginVO){
        String etoToken =  templateService.getEtoToken(true);
        String userInfo = acsControlModuleInvokeService.getLoginUserInfo();
        String userPhone = userInfo != null && !userInfo.equals("null") ? JSONObject.parseObject(userInfo).get("userCellphoneNo").toString() : "";

        MultiValueMap<String, Object> reqMap = new LinkedMultiValueMap<>();
        reqMap.add("etoToken", etoToken );
        reqMap.add("userType", loginVO.getUserType());
        reqMap.add("phone", userPhone);
        reqMap.add("uMac", loginVO.getUMac());
        reqMap.add("companyId", loginVO.getCompanyId());
        reqMap.add("serviceId", loginVO.getServiceId());
        log.info("appDoLogin map [{}]", reqMap.toString());
        ResultVO resultVO = RestTemplateUtils.sendRequest(commonHost+"/base/authLogin.do", reqMap ,
                ResultVO.class,"post");
        log.info("appDoLogin res [{}]",resultVO.toString() );
        if(resultVO != null){
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
//                AppUserInfoVO userInfoVO = JSONObject.parseObject( resultVO.getObject().toJSONString() , AppUserInfoVO.class);
                return new ResultEntity(CommonCodeEntity.SUC_CODE, "suc",resultVO.getObject() );
            }else {
                log.error("appDoLogin fail: " + resultVO.toString());
            }
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"fail","" );
    }

    @PostMapping("/selAcsInfo")
    public ResultEntity selAcsInfo(String ticket,Integer companyId,Integer serviceId ){
        MultiValueMap<String, Object> reqMap = new LinkedMultiValueMap<>();
        reqMap.add("ticket", ticket );
        reqMap.add("companyId", companyId );
        reqMap.add("serviceId", serviceId );
        reqMap.add("type", 2 );
        log.info("selAcsInfo map [{}] ",reqMap.toString());
        ResultVO resultVO = RestTemplateUtils.sendRequest(commonHost+"/wyOwner/gateLockList.do", reqMap ,
                ResultVO.class,"post");
        log.info("selAcsInfo resultVO [{}] ",resultVO.toString());
        if(resultVO != null){
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                List<AppAcsInfo> comList = JSON.parseArray( JSONArray.toJSONString(resultVO.getObject().get("data")) , AppAcsInfo.class);
                log.info(comList.toString());
                return new ResultEntity(CommonCodeEntity.SUC_CODE, "suc",comList);
            }else {
                log.error("selAcsInfo fail: " + resultVO.toString());
            }
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"fail","" );

    }

    @PostMapping("/appOpenDoor")
    public ResultEntity appOpenDoor(AppOpenDoorVO doorVO ){
        MultiValueMap<String, Object> reqMap = new LinkedMultiValueMap<>();
        reqMap.add("uId", doorVO.getUId() );
        reqMap.add("uMac", doorVO.getUMac());
        reqMap.add("devCode", doorVO.getDevCode());
        reqMap.add("ticket", doorVO.getTicket());
        reqMap.add("openType", 1);
        reqMap.add("companyId", doorVO.getCompanyId());
        reqMap.add("serviceId", doorVO.getServiceId());
        log.info("appOpenDoor map [{}] ",reqMap.toString());
        ResultVO resultVO = RestTemplateUtils.sendRequest(commonHost+"/wyOwner/openDoorRemote.do", reqMap ,
                ResultVO.class,"post");
        if(resultVO != null){
            log.info("appOpenDoor resultVO [{}] ",resultVO.toString());
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                return new ResultEntity(CommonCodeEntity.SUC_CODE, "开门成功","");
            }else {
                log.error("appOpenDoor fail: " + resultVO.toString());
                return new ResultEntity(CommonCodeEntity.FAIL,resultVO.getRstDesc(),"" );
            }
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"fail","" );
    }

    @PostMapping("/queryFaces")
    public ResultEntity queryFaces(String ticket, String companyId,String serviceId ){
        MultiValueMap<String, Object> reqMap = new LinkedMultiValueMap<>();
        reqMap.add("ticket", ticket );
        reqMap.add("companyId", companyId );
        reqMap.add("serviceId", serviceId );
        log.info("queryFaces map [{}] ",reqMap.toString());
        AppResultVO resultVO = RestTemplateUtils.sendRequest(commonHost+"/face/queryFaces.do", reqMap ,
                AppResultVO.class,"post");
        if(resultVO != null){
            log.info("queryFaces resultVO [{}] ",resultVO.toString());
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                List<AppFaceInfoVO> comList = JSON.parseArray( JSONArray.toJSONString(resultVO.getObject()) , AppFaceInfoVO.class);
                log.info(comList.toString());
                return new ResultEntity(CommonCodeEntity.SUC_CODE, "suc",comList);
            }else {
                log.error("queryFaces fail: " + resultVO.toString());
            }
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"fail","" );
    }


    @PostMapping("/updateFaces")
    public ResultEntity updateFaces(String ticket, String companyId, String serviceId, Integer fafId, MultipartFile file){
        MultiValueMap<String, Object> reqMap = new LinkedMultiValueMap<>();
        reqMap.add("ticket", ticket );
        reqMap.add("companyId", companyId );
        reqMap.add("serviceId", serviceId );
        if(fafId != 0){
            reqMap.add("fafId", fafId );
        }
        log.info("updateFaces map [{}] ",reqMap.toString());
        byte[] bytesArray = new byte[(int) file.getSize()];
        InputStream fis = null;
        try {
            fis =  file.getInputStream();
            fis.read(bytesArray); //read file into bytes[]
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) {
            @Override
            public String getFilename() {
                return "file.jpg";
            }
        };
        reqMap.add("file", contentsAsResource);
        RestTemplate restTemplate = new RestTemplate();
        JSONObject json = restTemplate.postForObject(commonHost+"/face/extractFileFaceFeature.do", reqMap, JSONObject.class);
        log.info("updateFaces json:"+json );
        AppResultVO resultVO = JSONObject.parseObject(json.toJSONString(),AppResultVO.class );
//        ResultVO resultVO = RestTemplateUtils.sendRequest(commonHost+"/face/extractFileFaceFeature.do", reqMap ,
//                ResultVO.class,"post");
        if(resultVO != null){
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                return new ResultEntity(CommonCodeEntity.SUC_CODE, "suc",imgHost+resultVO.getRstDesc());
            }else {
                log.error("updateFaces fail: " + resultVO.toString());
                return new ResultEntity(CommonCodeEntity.FAIL,resultVO.getRstDesc(),"" );
            }
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"fail","" );
    }



}
